package day14;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xinxing
 * @date 2022/10/10 14:30
 */
public class ScheduledExecutorServiceDemo {

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);

    void runnable() {
        ScheduledFuture<?> schedule = executorService.schedule(() -> System.out.println(getDate() + " schedule Runnable"),
                3, TimeUnit.SECONDS);
        try {
            System.out.println(getDate() + " runnable result: " + schedule.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    void callable() {
        ScheduledFuture<String> schedule = executorService.schedule(() -> {
            Thread.sleep(5000);
            return "callable";
        }, 1, TimeUnit.SECONDS);
        String s = null;
        try {
            s = schedule.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(getDate() + " callable result: " + s);

    }

    void scheduleAtFixedRate() {
        AtomicInteger i = new AtomicInteger();
        executorService.scheduleAtFixedRate(() -> {
            i.getAndIncrement();
            System.out.println(getDate() + " scheduleAtFixedRate: " + i);
        }, 3000, 5000, TimeUnit.MILLISECONDS);
    }

    void scheduleWithFixedDelay() {
        AtomicInteger i = new AtomicInteger();
        executorService.scheduleWithFixedDelay(() -> {
            i.getAndIncrement();
            System.out.println(getDate() + " scheduleWithFixedDelay: " + i);
        }, 1000, 5000, TimeUnit.MILLISECONDS);
    }

    private String getDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return sdf.format(date);
    }

    public static void main(String[] args) {
        ScheduledExecutorServiceDemo serviceDemo = new ScheduledExecutorServiceDemo();
        System.out.println("begin: " + serviceDemo.getDate());
        serviceDemo.runnable();
        serviceDemo.callable();
        serviceDemo.scheduleAtFixedRate();
        serviceDemo.scheduleWithFixedDelay();
    }
}
